using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Test.Models;
using Test.Repository;
using Test.Request;
using System.Collections.Generic;
namespace Test.Controllers
{
    public class TestController : Controller
    {
        public IActionResult Index()
        {
            var ef = new EfRepository<Commodity>();
            var commodity = ef.Table.Where(x => x.IsDeleted == false).ToList();

            return View(commodity);
        }

        public IActionResult Delete(int id)
        {
            var ef = new EfRepository<Commodity>();

            ef.Delete(id);
            return RedirectToAction("Index");
        }
        public IActionResult Add()
        {
            return View("Create");
        }
        public IActionResult Insert(CommodityRequest model)
        {
            var ef = new EfRepository<Commodity>();

            ef.Insert(
            new Commodity
            {
                ProductName = model.ProductName,
                Supplier = model.Supplier,
                Price = model.Price,
                Stock = model.Stock,
                Remarks = model.Remarks
            }
            );
            return Ok();
        }
        public IActionResult Update(int id)
        {
            var ef = new EfRepository<Commodity>();
            var commodity = ef.GetById(id);
            return View("Update", commodity);
        }
        public IActionResult Save(CommodityRequest model)
        {
            var ef = new EfRepository<Commodity>();
            var commodity = ef.GetById(model.Id);

            commodity.ProductName = model.ProductName;
            commodity.Supplier = model.Supplier;
            commodity.Price = model.Price;
            commodity.Stock = model.Stock;
            commodity.Remarks = model.Remarks;

            ef.Update(commodity);

            return Ok();
        }

        public IActionResult find(KeywordRequest model)
        {

            IEnumerable<Commodity> commodity;
            var ef = new EfRepository<Commodity>();
            if (model != null && model.keyword != null && model.keyword.Length > 0)
            {
                commodity = ef.Table
                            .Where(x => x.IsDeleted == false && x.ProductName.Contains(model.keyword) || x.Remarks.Contains(model.keyword))
                            .ToList();
            }
            else
            {
                commodity = ef.Table
                .Where(x => x.IsDeleted == false)
                .ToList();
            }
            return Json(commodity);
        }

    }
}